package com.zwxu.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Graph{
    public boolean isDag = true;

    private List<GraphNode> graphNodeList;

    public List<GraphNode> getGraphNodeList() {
        return graphNodeList;
    }

    public void setGraphNodeList(List<GraphNode> graphNodeList) {
        this.graphNodeList = graphNodeList;
    }

    public Map<String,Integer> initMap = new HashMap<String,Integer>();

    private void initMap(){
        for(GraphNode graphNode:graphNodeList){
            initMap.put(graphNode.getName(),0);
        }
    }

    public boolean checkDag(){
        boolean flag = true;
        initMap();
        for(GraphNode graphNode:graphNodeList){
            if(initMap.get(graphNode.getName()).equals(-1)){
                continue;
            }
            isDag(graphNode);
            if(!isDag){
                System.out.println(String.format("%s出现有环",graphNode.getName()));
                flag = false;
                break;
            }
        }
        return flag;
    }

    private void isDag(GraphNode graphNode){
        initMap.put(graphNode.getName(),1);
        for(GraphNode node:graphNodeList){
            if(graphNode.getIndegreeNodeName() != null && graphNode.getIndegreeNodeName().contains(node.getName())){
                if(initMap.get(node.getName()).equals(1)){
                    isDag = false;
                    //return false;
                    break;
                }else if(initMap.get(node.getName()).equals(-1)){
                    continue;
                }else{
                    isDag(node);
                }
            }
        }
        initMap.put(graphNode.getName(),-1);
    }
}
